#!/usr/bin/perl -w
use strict;

use DBI;
use URI::Escape;
use HTML::Entities;

our $h=DBI->connect('DBI:mysql:database=Down','root') || die $DBI::errstr;
our $ns;
$_=$ENV{'QUERY_STRING'}||'';
my $size;
$size=$1 if s/^size=(\d+)&//;
if (s/^url=//){

} elsif (s/^furl=//){
s/\+/ /g;#s/\%([0-9a-f]{2})/chr(hex($1))/ige;
}
$_=uri_unescape($_);

s{^ubuntu/|^.*http://cdit(?:|\:\d+)/ubuntu/}{http://archive.ubuntu.com/ubuntu/};

my $Result="<?xml version='1.0' encoding='utf-8'?><?xml-stylesheet type='text/xsl' href='list.xsl'?>\n<GQ>\n";

if ($_)
{
$ns=$h->prepare(qq/insert into down (url,size) values (?,?)/);

$Result.=sprintf <<EOF, encode_entities($_), $size||0;
<Question>
    <url>%s</url>
    <size>%s</size>
</Question>
EOF

$ns->execute($_,$size);
$ns->finish();
}

unless (-t STDIN)
{

my ($lm)=$h->selectrow_arrayref(qq/show table status like 'down'/);

#use POSIX qw(strftime);
#use Time::Local qw(timelocal);
#my @dt=split/[ :-]/,$$lm[11];
#$lm = timelocal(@dt[5,4,3,2,1,0]);
use HTTP::Date qw(time2str str2time);
#$lm = strftime "%a, %d %b %Y %H:%M:%S GMT", gmtime($lm);
#Last-Modified: Fri, 28 Sep 2007 13:11:48 GMT
#0    1  2  3  4  5
#2008-02-08 10:23:39

my $tn=str2time($$lm[12]);

if($ENV{'HTTP_IF_MODIFIED_SINCE'})
{
    my $ls=str2time($ENV{'HTTP_IF_MODIFIED_SINCE'});
#    unless ($tn>$ls)
    if ($tn==$ls)
    {
#	print STDERR "Modify: $tn, $ls: $$lm[12], $ENV{'HTTP_IF_MODIFIED_SINCE'}\n";
	print "Status: 304 Not Modified\n\n";
	exit;
    }
}

$tn=time2str($tn);
my $age=0;
my $ttm=time2str(time()+$age);

$Result="Expires: $ttm\nCache-Control: max-age=$age; must-revalidate\nLast-Modified: $tn\nContent-Type: text/xml\n\n".$Result;
}

#; no-store; no-cache\nPragma: no-cache

$ns=$h->prepare(qq/select id,prio,size,url from down where status=0 order by prio desc,id desc/);
$ns->execute();

my @has;
print $Result."<queue>\n";
print "\t<el ".join(' ',map "$_='".encode_entities(shift(@has))."'",@{$ns->{NAME}})."/>\n" while @has=$ns->fetchrow_array();
print "</queue>\n</GQ>\n";

$ns->finish();
$h->disconnect();
